<?php
require_once 'streamconfig.php';
class Linestream extends Streamconfig
{
    //订单分润表别名（固定三张表）
    protected $price_profit;
    protected $bargaining;
    protected $user;
    
    public $orderPayTotal; //议价时的订单支付。
    public $home_price = 0;//单房差。
    public $pay_style_scale = 1; //支付百分比

    //分润必要参数
    protected $sellerUid;       //购买者uid
    protected $bitTrade;        //购买者用户的类型
    protected $orderId;         //订单ID
    protected $priceId;         //产品的id
    protected $adultNumber = 0; //成人购买数量
    protected $childNumber = 0; //儿童购买数量
    protected $bitWan;          //1:在线支付；2：到付
    
    protected $number;          //当前数量
    protected $isAdult;         //1:成人；2：儿童
    
    public function __construct($tables = array())
    {
        parent::__construct();
        if (count($tables) > 0) {
            $this->initialize($tables);
        }
    }
    
    /**
     * 初始化数据
     * @param unknown $props
     */
    public function initialize($tables)
    {
        foreach ($tables as $alias=>$table) {
            $this->CI->load->model($table.'_model', $table);
            $this->$alias = $this->CI->$table; //给表别名赋值
        }
    }
    
    public function executeLineProfit($parameter=array())
    {
        if (!$this->validateChkValue($parameter)) {
            $this->setError('参数不正确！');
            return ;
        }
        $result = $this->bargaining->findByArray(array('seller_uid'=>$this->sellerUid, 'price_id'=>$this->priceId));
        if ($result->num_rows() > 0) { /** 如果议价了。*/
            $orderProfit = $this->bargainingProfit($result->row());
        } else { /** 走正常分润流程。*/
            $this->number     = $this->adultNumber;
            $this->isAdult    = 1; //成人
            $orderProfitAdult = $this->executeProfit();
            if ($this->childNumber > 0) {
                $this->number     = $this->childNumber;
                $this->isAdult    = 2; //儿童
                $this->home_price = 0; //单房差设为零
                $orderProfitChild = $this->executeProfit();
    
            }
            if (!empty($orderProfitAdult) && !empty($orderProfitChild)) {
                $orderProfit = $this->dealwithOrderProfitData($orderProfitAdult, $orderProfitChild);
            } else {
                $orderProfit = $orderProfitAdult;
            }
            $error = $this->getError();
            if (!empty($error)) {
                return ;
            }
        }
        return $orderProfit;
    }
    
    /**
     * 验证参数。
     * @param unknown $parameter
     * @return boolean
     */
    private function validateChkValue($parameter)
    {
        $sysParameter = array('sellerUid', 'bitTrade', 'priceId', 'adultNumber', 'childNumber', 'bitWan', 'home_price', 'pay_style_scale');
        foreach ($sysParameter as $kv) {
            if (!isset($parameter[$kv])) {
                return false;
            }
            $this->$kv = $parameter[$kv];
        }
        return true;
    }
    
    /**
     * 比较两个数组的值，将数组中的金额相加并取交集。
     * @param array $orderProfitAdult
     * @param array $orderProfitChild
     * @return Ambigous <multitype:, multitype:unknown >
     */
    private function dealwithOrderProfitData($orderProfitAdult, $orderProfitChild)
    {
        $orderProfit = array();
        foreach ($orderProfitAdult as $key=>$value) {
            if (array_key_exists($key, $orderProfitChild)) {
                $orderProfitAdult[$key] = $value;
                $orderProfitAdult[$key]['account'] += $orderProfitChild[$key]['account'];
                unset($orderProfitChild[$key]);
            }
            $orderProfit[] = $value;
        }
        $orderProfit = array_merge($orderProfitAdult, $orderProfitChild);
        return $orderProfit;
    }
    
    /**
     * 获取订单分润表所需要的数据
     * @return void|Ambigous <void, unknown>
     */
    public function executeProfit()
    {
        //没有议价，直接分润
        $result = $this->price_profit->findPriceProfit(array('status'=>'profit', 'allot_id'=>$this->priceId, 'level'=>$this->isAdult));
        if ($result->num_rows() <= 0) {
            if ($this->isAdult==1) {
                $this->setError('该产品不可购买');
            } else {
                $this->setError('不可购买儿童票');
            }
            return ;
        }
        return $this->getOrderProfitData($result->result());
    }
    
    public function getOrderProfitData($profitObj)
    {
        $targets = $this->getTargets($this->sellerUid); //购买者uid
        if (empty($targets)) {
            $this->setError('获取不到账户的上级用户');
            return ;
        }
        foreach ($profitObj as $key=>$value) {  //确定分钱的人
            if ($value->bit_trade != UTID_PROVIDER && $value->bit_trade != UTID_PURCHASER && $value->uid == 0) { //如果用户类型不是“供货商”，也不是“采购商”
                $value->uid = $this->firstTarget($value->bit_trade, $targets);
            }
            $profitObj[$key] = $value;
        }
     
        return $this->orderProfitDetails($profitObj);
    }
    
    private function orderProfitDetails($profitObj)
    {
        if ($this->bitWan == 1) {//在线
            return $this->onlinePaymentProfit($profitObj);
        } else if ($this->bitWan == 2) {
            return $this->arrivalPaymentProfit($profitObj);
        }
    }
    
    /**
     * 在线支付
     * 最终确定分钱的人 和  如果为购买者分销商的话，就直接把分的钱扣在实际支付的价钱
     * @param unknown $profitObj
     */
    private function onlinePaymentProfit($profitObj)
    {
        $orderProfit   = array();
        $salePrice     = 0; //销售价
        $providerPrice = 0; //供应价
        $reseller      = 0; //分销商利润(当前购买者)
        foreach ($profitObj as $key=>$value) {
            //购买者区别对待。//如果用户类型不同 并且 用户uid不相等
            switch ($value->bit_trade) {
                case UTID_PROVIDER://如果是供应商，获取供应价
                    $providerPrice = $value->amount*$this->number;
                    $orderProfit[$value->uid]['uid']          = $value->uid;
                    $orderProfit[$value->uid]['account']      = ($value->amount*$this->number + $this->home_price)*$this->pay_style_scale;
                    $orderProfit[$value->uid]['account_type'] = ACCOUNT_TYPE_CARRY;
                    $orderProfit[$value->uid]['as']           = 1;
                    $orderProfit[$value->uid]['bit_trade']    = $value->type_id;
                    break;
                case UTID_MANAGER_L1://如果是购买者是分销商，也可能是发展商，也可能是一级或二级代理
                case UTID_MANAGER_L2:
                case UTID_GROWTH:
                case UTID_SELLER:
                    if ((int)$this->bitTrade&$value->bit_trade) {
                        $reseller += $value->amount*$this->number;
                    } else if ($value->uid != $this->sellerUid) {
                        $orderProfit[$value->uid]['uid']          = $value->uid;
                        if (isset($orderProfit[$value->uid])) { //判别用户级别是否同一个人，如果是同一个人则利润累加
                            $orderProfit[$value->uid]['account'] += $value->amount*$this->number;
                        } else {
                            $orderProfit[$value->uid]['account']  = $value->amount*$this->number;
                        }
                        $orderProfit[$value->uid]['account_type'] = ACCOUNT_TYPE_CARRY;
                        $orderProfit[$value->uid]['as']           = 1;
                        $orderProfit[$value->uid]['bit_trade']    = $value->type_id;
                    }
                    break;
                default: //
                    $orderProfit[$value->uid]['uid']          = $value->uid;
                    $orderProfit[$value->uid]['account']      = $value->amount*$this->number;
                    $orderProfit[$value->uid]['account_type'] = ACCOUNT_TYPE_CARRY;
                    $orderProfit[$value->uid]['as']           = 1;
                    $orderProfit[$value->uid]['bit_trade']    = $value->type_id;
            }
            $salePrice += $value->amount*$this->number;
        }
        $this->orderPayTotal += $salePrice - $reseller; //当前实际应支付金额 - 这个分销商所分的钱  ---- 注意：大人小孩，累计加一次
        return $orderProfit;
        
    }
    /*
     * 到付 -- 供应商 要给我们钱
     */
    private function arrivalPaymentProfit($profitObj)
    {
        $orderProfit   = array();
        $salePrice     = 0; //销售价总价
        $providerPrice = 0; //供应价 x 数量
        $providerUid   = 0; //供应商uid
        $profitPrice   = 0; //到付，供应商要返给我们利润钱
        $reseller      = 0; //分销商利润 x 数量
        foreach ($profitObj as $key=>$value) {
            //购买者区别对待。
            switch ($value->bit_trade) {
                case UTID_PROVIDER://如果是供应商，获取供应价
                    $providerPrice = $value->amount*$this->number;
                    $providerUid   = $value->uid;
                    break;
                case UTID_MANAGER_L1://如果是购买者是分销商，也可能是发展商，也可能是一级或二级代理
                case UTID_MANAGER_L2:
                case UTID_GROWTH:
                case UTID_SELLER:
                    if ((int)$this->bitTrade&$value->bit_trade) {
                        $reseller += $value->amount*$this->number;
                    } else if ($value->uid != $this->sellerUid) {
                        $orderProfit[$value->uid]['uid']          = $value->uid;
                        if (isset($orderProfit[$value->uid])) { //判别用户级别是否同一个人，如果是同一个人则利润累加
                            $orderProfit[$value->uid]['account'] += $value->amount*$this->number;
                        } else {
                            $orderProfit[$value->uid]['account']  = $value->amount*$this->number;
                        }
                        $orderProfit[$value->uid]['account_type'] = ACCOUNT_TYPE_MONTH;
                        $orderProfit[$value->uid]['as']           = 1;
                        $orderProfit[$value->uid]['bit_trade']    = $value->type_id;
                    }
                    break;
                default: //
                    $orderProfit[$value->uid]['uid']          = $value->uid;
                    $orderProfit[$value->uid]['account']      = $value->amount*$this->number;
                    $orderProfit[$value->uid]['account_type'] = ACCOUNT_TYPE_MONTH;
                    $orderProfit[$value->uid]['as']           = 1;
                    $orderProfit[$value->uid]['bit_trade']    = $value->type_id;
            }
            $salePrice += $value->amount*$this->number;
        }
        //到付，供应商要返给我们利润钱
        $profitPrice += $salePrice - $providerPrice - $reseller;
        if ($profitPrice > 0) {
            $orderProfit[$providerUid]['uid']          = $providerUid;
            $orderProfit[$providerUid]['account']      = $profitPrice;
            $orderProfit[$providerUid]['account_type'] = ACCOUNT_TYPE_MONTH;
            $orderProfit[$providerUid]['as']           = 2;
            $orderProfit[$providerUid]['bit_trade']    = UTID_PROVIDER;
        }
        $this->orderPayTotal += $salePrice - $reseller; //当前实际应支付金额 - 这个分销商所分的钱 ---- 注意：大人小孩，累计加一次
        return $orderProfit;
    }
    
    public function bargainingProfit($bargainingRow)
    {
        $bargainingProfit = $this->price_profit->findPriceProfit(array('status'=>'bargaining', 'allot_id'=>$bargainingRow->bargaining_id)); //不区分大人小孩
        if ($bargainingProfit->num_rows() <= 0) {
            $bargainingProfit = array(); //$this->setError('该产品议价了，但没有设置议价分润');
        } else {
            $bargainingProfit = $bargainingProfit->result();
        }
    
        if ($this->bitWan == '1') {//在线
             
            return $this->onlinePaymentBargaining($bargainingRow, $bargainingProfit);
        } elseif ($this->bitWan == '2') {
            return $this->arrivalPaymentBargaining($bargainingRow, $bargainingProfit);
        }
    }
    
    private function onlinePaymentBargaining($bargainingRow, $bargainingProfit)
    {
        $orderProfit = array();
        if (!empty($bargainingProfit)) {
            foreach ($bargainingProfit as $key=>$value) {
                $orderProfit[$value->uid]['uid']          = $value->uid;
                $orderProfit[$value->uid]['account']      = $value->amount*($this->adultNumber + $this->childNumber);
                $orderProfit[$value->uid]['account_type'] = ACCOUNT_TYPE_CARRY;
                $orderProfit[$value->uid]['bit_trade']    = $value->type_id;
                $orderProfit[$value->uid]['as']           = 1;
            }
        }
        if ($bargainingRow->node == 'system') { //系统结算
            $this->home_price = $this->home_price > 0 ? $bargainingRow->home_price : 0;
            //给供应商分钱 -- 供应价+单房差
            $orderProfit[$bargainingRow->provider_uid]['uid']          = $bargainingRow->provider_uid;
            $orderProfit[$bargainingRow->provider_uid]['account']      = (($bargainingRow->adult_price*$this->adultNumber) + ($bargainingRow->children_price*$this->childNumber)+$this->home_price)*$this->pay_style_scale;
            $orderProfit[$bargainingRow->provider_uid]['account_type'] = ACCOUNT_TYPE_CARRY;
            $orderProfit[$bargainingRow->provider_uid]['bit_trade']    = UTID_PROVIDER;
            $orderProfit[$bargainingRow->provider_uid]['as']           = 1;
            
            switch ($bargainingRow->payer) {
                case 'seller' : //分销商付手续费
                    $amountTotal   = ($bargainingRow->adult_price + $bargainingRow->poundage + $bargainingRow->prosecond_profit)*$this->adultNumber +
                                     ($bargainingRow->children_price + $bargainingRow->poundage + $bargainingRow->prosecond_profit)*$this->childNumber;
                    //分销商付手续费，已经多付了手续费的钱，不需要分钱的时候减掉
                    //$orderProfit[$bargainingRow->seller_uid] = $this->getOrderProfitPayer($bargainingRow, $bargainingRow->seller_uid, UTID_SELLER);
                   break;
                case 'provider' : //供应商付手续费
                    $amountTotal   = ($bargainingRow->adult_price + $bargainingRow->prosecond_profit)*$this->adultNumber +
                                     ($bargainingRow->children_price + $bargainingRow->prosecond_profit)*$this->childNumber;
                    $orderProfit[$bargainingRow->provider_uid]['account'] = $orderProfit[$bargainingRow->provider_uid]['account'] + $bargainingRow->poundage * ($this->adultNumber + $this->childNumber);
                    break;
                case 'prosecond' ://二级供应商付手续费
                    $amountTotal   = ($bargainingRow->adult_price + $bargainingRow->prosecond_profit)*$this->adultNumber +
                                     ($bargainingRow->children_price + $bargainingRow->prosecond_profit)*$this->childNumber;
                    $orderProfit[$bargainingRow->prosecond_id] = $this->getOrderProfitOnlinePayer($bargainingRow, $bargainingRow->prosecond_id, UTID_SELLER);
                    break;
            }
            $this->orderPayTotal = $amountTotal + ($amountTotal * ($bargainingRow->bankpay/100));
        } else /*if ($bargainingRow->node == 'private')*/ { //自主结算
            $this->orderPayTotal = $bargainingRow->poundage * ($this->adultNumber + $this->childNumber);
        }
        return $orderProfit;
        
    }
    
    /**
     * 议价在线支付-减去指定的手续费
     * @param unknown $bargainingRow
     * @param unknown $payerUid
     * @param unknown $type_id
     * @return multitype:number string unknown NULL
     */
    private function getOrderProfitOnlinePayer($bargainingRow, $payerUid, $type_id)
    {
        $orderProfit = array(
            'order_id'     => $this->orderId,
            'uid'          => $payerUid,
            'account'      => $bargainingRow->poundage * ($this->adultNumber + $this->childNumber),
            'account_type' => ACCOUNT_TYPE_CARRY,
            'bit_trade'    => $type_id,
            'as'           => 2
        );
        return $orderProfit;
    }
    
    /**
     * 到付，不存在自主结算和系统结算。
     * 到付，我们就只收手续费分润钱，不存在收取银行利息
     * @param unknown $bargainingRow
     * @param unknown $bargainingProfit
     * @return Ambigous <number, multitype:multitype:number Ambigous <multitype:number, multitype:number string unknown NULL > >
     */
    private function arrivalPaymentBargaining($bargainingRow, $bargainingProfit)
    {
        $orderProfit = array();
        $otherPoundage = 0; //手续费 - 分给着想的手续费利润
        if (!empty($bargainingProfit)) {
            foreach ($bargainingProfit as $key=>$value) {
                if ($value->type_id != UTID_BEIZHU) {
                    $otherPoundage += $value->amount*($this->adultNumber + $this->childNumber);
                }
                $orderProfit[$value->uid]['uid']          = $value->uid;
                $orderProfit[$value->uid]['account']      = $value->amount*($this->adultNumber + $this->childNumber);
                $orderProfit[$value->uid]['account_type'] = ACCOUNT_TYPE_MONTH;
                $orderProfit[$value->uid]['bit_trade']    = $value->type_id;
                $orderProfit[$value->uid]['as']           = 1;
            }
        }
        switch ($bargainingRow->payer) {
            case 'seller' : //分销商付手续费,到付给供应商，还是供应商欠我们手续费的钱
                $amountTotal   = ($bargainingRow->adult_price + $bargainingRow->poundage + $bargainingRow->prosecond_profit)*$this->adultNumber +
                                 ($bargainingRow->children_price + $bargainingRow->poundage + $bargainingRow->prosecond_profit)*$this->childNumber;
                if ($otherPoundage > 0) {
                    $orderProfit[$bargainingRow->provider_uid] = $this->providerPayTotalArrivalPayer($bargainingRow->provider_uid, $otherPoundage, UTID_PROVIDER);
                }
                break;
            case 'provider' : //供应商付手续费，是供应商付我们的钱
                $amountTotal   = ($bargainingRow->adult_price  + $bargainingRow->prosecond_profit)*$this->adultNumber +
                                 ($bargainingRow->children_price  + $bargainingRow->prosecond_profit)*$this->childNumber;
                if ($otherPoundage > 0) {
                    $orderProfit[$bargainingRow->provider_uid] = $this->providerPayTotalArrivalPayer($bargainingRow->provider_uid, $otherPoundage, UTID_PROVIDER);
                }
                break;
            case 'prosecond' ://二级供应商付手续费，是二级供应商欠我们钱，但是二级供应商的账户余额必须要大于这个钱。
                $amountTotal   = ($bargainingRow->adult_price + $bargainingRow->prosecond_profit)*$this->adultNumber +
                                 ($bargainingRow->children_price + $bargainingRow->prosecond_profit)*$this->childNumber;
                if ($otherPoundage > 0) {
                    $orderProfit[$bargainingRow->prosecond_id] = $this->providerPayTotalArrivalPayer($bargainingRow->prosecond_id, $otherPoundage, UTID_SELLER);
                }
                break;
        }
        $this->home_price = $this->home_price > 0 ? $bargainingRow->home_price : 0; //单房差
        //这里是分销商(当前用户)要付给供应商多少钱？。
        $this->orderPayTotal = $amountTotal;
        return $orderProfit;
    }
    
    /**
     * 供应商要给我们多少钱？
     * @param unknown $bargainingRow
     */
    public function providerPayTotalArrivalPayer($userUid, $otherPoundage, $bit_trade)
    {
        $orderProfit = array(
            'uid'          => $userUid,
            'account'      => $otherPoundage,
            'account_type' => ACCOUNT_TYPE_MONTH,
            'bit_trade'    => $bit_trade,
            'as'           => 2
        );
        return $orderProfit;
    }
}